<template>
    <div>
        <div class="tableHeadBox">
            <div class="buttonBox">
                <el-button v-if="isLabAdmin" class="addButton" type="primary" size="small" @click="ClickAdd">添加检查</el-button>
                <el-select v-model="seleteBuildingId" placeholder="请选择楼栋" style="width: 150px" size="small">
                    <el-option v-for="item in allBuilding" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
                <el-select v-model="seleteSemesterId" placeholder="请选择学期" style="width: 150px" size="small">
                    <el-option v-for="item in allSemester" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
            </div>
            <div class="searchBox">
                <el-button type="warning" size="small" style="margin-right: 20px;"
                    @click="ClickExportList">导出Excel</el-button>
                <el-input class="searchInput" v-model="searchStr" size="small" placeholder="请输入实验室名"></el-input>
                <el-button class="searchButton" type="primary" size="small" :icon="Search">搜索</el-button>
            </div>
        </div>

        <!--#region 列表 -->
        <div class="tableBox">
            <el-table ref="multipleTableRef" :data="filterTableData" height="100%" style="width: 100%">
                <el-table-column type="selection" width="55" />
                <el-table-column prop="id" label="ID"></el-table-column>
                <el-table-column prop="dateTime" label="时间" width="180"></el-table-column>
                <el-table-column prop="semesterName" label="学期"></el-table-column>
                <el-table-column prop="adminName" label="管理员"></el-table-column>
                <el-table-column prop="labName" label="教室"></el-table-column>
                <el-table-column prop="state" label="状态">
                    <template v-slot="scope">
                        <el-tag type="success" v-if="scope.row.state">正常</el-tag>
                        <el-tag type="error" v-else>异常</el-tag>
                    </template>
                </el-table-column>
                <!-- 按钮 -->
                <el-table-column fixed="right" label="操作" width="330">
                    <template #default="scope">
                        <el-button round type="success" size="small"
                            @click="ClickViewDetail(scope.$index, scope.row)">查看详情</el-button>
                        <el-button v-if="isLabAdmin" round type="primary" size="small"
                            @click="ClickEdit(scope.$index, scope.row)">编辑</el-button>
                        <el-button round type="warning" size="small"
                            @click="ClickExport(scope.$index, scope.row)">导出Excel</el-button>
                        <el-button v-if="isLabAdmin" round type="danger" size="small"
                            @click="ClickDelete(scope.$index, scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <!-- #endregion -->
    </div>

    <!--编辑/添加弹窗 -->
    <el-dialog v-model="dialogVisible" :title="currentBuilding == null ? '添加学院' : '编辑学院'" width="800" top="3vh"
        :close-on-press-escape="false">
        <CheckForm v-if="dialogVisible" :Close="Close" :transmitObj="currentBuilding" :isShow="isShow"></CheckForm>
    </el-dialog>

</template>

<script setup>
import service from '@/request';
import '../assets/css/table.css'
import { Search } from '@element-plus/icons-vue'
import { reactive, ref, computed, onBeforeMount, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import CheckForm from '@/components/Check/CheckForm.vue';

let isSuperAdmin = ref(false)//超级管理员
let isLabAdmin = ref(false)//实验室管理员

// #region 显示提示
async function ShowTip(isSuccess, msg) {
    if (isSuccess == true) {
        ElMessage({ message: msg, type: 'success' })
    }
    else {
        ElMessage({ message: msg, type: 'error' })
    }
}
//#endregion


//获取数据
let tableData = reactive([])
async function getDataList() {
    let resultData = []
    let url = "/Check/getAllCheck"
    if (isSuperAdmin.value == true) {
        url = "/Check/getAllCheck"
    }
    if (isLabAdmin.value == true) {
        let userId = localStorage.getItem('userId')
        url = "/Check/getCheckByUserId?id=" + userId
    }
    await service.get(url).then(
        (res) => {
            resultData.push(...res.value)
        }
    )
    return resultData
}


//搜索
let searchStr = ref('')
const filterTableData = computed(() =>
    tableData.filter(
        (data) =>
            (!searchStr.value || data.labNumber.toLowerCase().includes(searchStr.value.toLowerCase())) &&
            (seleteSemesterId.value == 0 || data.semesterId == seleteSemesterId.value) &&
            (seleteBuildingId.value == 0 || data.buildingId == seleteBuildingId.value)
    )
)

//查看详情
let isShow = ref(false)
async function ClickViewDetail(index, row) {
    isShow.value = true
    currentBuilding = row;
    dialogVisible.value = true;
}

//添加/编辑
let currentBuilding = null;
let dialogVisible = ref(false)
async function ClickAdd() {
    isShow.value = false
    currentBuilding = null;
    dialogVisible.value = true;
}
async function ClickEdit(index, row) {
    isShow.value = false
    currentBuilding = row;
    dialogVisible.value = true;
}
async function Close() {
    currentBuilding = null;
    dialogVisible.value = false;
    await Reload()
}

//点击导出
async function ClickExport(index, row) {
    await service.post(`/Mangment/exportExcel`, [row]).then(
        async res => {
            ShowTip(true, "操作成功")
            window.open(res)
        },
        error => {
            ShowTip(false, error)
        }
    )
}
let multipleTableRef = ref()
async function ClickExportList(index, row) {
    let data = multipleTableRef.value.getSelectionRows()
    await service.post(`/Mangment/exportExcel`, data).then(
        async res => {
            ShowTip(true, "操作成功")
            window.open(res)
        },
        error => {
            ShowTip(false, error)
        }
    )

}



//删除
async function ClickDelete(index, row) {
    await ElMessageBox.confirm(
        '你确定要这么做吗，这样做将无法撤回?',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(async () => {
        service.delete("/Check/deteleCheck?checkId=" + row.id).then(
            async res => {
                ShowTip(true, '删除成功')
                await Reload()
            },
            error => {
                ShowTip(false, '删除失败')
            }
        )
    }).catch(() => {
        ShowTip(false, '取消删除')
    })
}


//获取学期
let seleteSemesterId = ref(0)
let allSemester = reactive([{ id: 0, name: '全部学期' }])
async function getSemesterDataList() {
    let resultData = []
    await service.get("/Mangment/getAllSemester").then(
        (res) => {
            resultData.push(...res.value)
        }
    )
    return resultData
}


//获取楼栋
let seleteBuildingId = ref(0)
let allBuilding = reactive([{ id: 0, name: '全部楼栋' }])
async function getBuildingDataList() {
    let resultData = []
    await service.get("Building/getAllBuilding").then(
        (res) => {
            resultData.push(...res.value)
        }
    )
    return resultData
}


async function Reload() {
    let roleName = localStorage.getItem('roleName')
    if (roleName == '超级管理员') {
        isSuperAdmin.value = true
    }
    if (roleName == '实验室管理员') {
        isLabAdmin.value = true
    }

    tableData.length = 0
    tableData.push(...await getDataList())
    allSemester.push(...await getSemesterDataList())
    allBuilding.push(...await getBuildingDataList())
}

onBeforeMount(async () => {
    await Reload()
})


</script>
<style scoped>
.el-radio {
    margin-top: 10px;
    width: 250px;
}

.buttonBox {
    float: left;
    height: 40px;
    padding-top: 10px;
    margin-left: 20px;
}

.searchInput,
.addInput {
    width: 200px;
}

.searchButton,
.addButton {
    margin-left: 10px;
}
</style>